package org.rapan;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.rapan.EJB.CompanyInt;
import org.rapan.exceptions.EmailTakenException;

import com.vaadin.data.validator.EmailValidator;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Form;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Window.Notification;

@SuppressWarnings("serial")
public class CompanyForm extends Form {

	TextField companyName = new TextField("Company Name:");
	TextField companyEmail = new TextField("Company Email:");

	public CompanyForm() {
		getLayout().setMargin(true);
		addField("companyName", companyName);
		companyName.setRequired(true);
		companyEmail.setRequired(true);
		companyEmail.setImmediate(true);
		companyEmail.addValidator(new EmailValidator("Invalid Email"));
		addField("companyEmail", companyEmail);
		Button submitButton = new Button("Submit");
		addField("submit", submitButton);

		submitButton.addListener(new ClickListener() {

			public void buttonClick(ClickEvent event) {
				if (isValid()) {
					try {
						InitialContext context = new InitialContext();
						CompanyInt comInt = (CompanyInt) context
								.lookup("Consult/CompanyBean/local");
						comInt.createCompany((String) companyName.getValue(),
								(String) companyEmail.getValue());
						clearForm();
						Notification not = new Notification("Company added.");
						not.setDelayMsec(100 * 20);
						getWindow().showNotification(not);

					} catch (NamingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (EmailTakenException e) {
						getWindow().showNotification("Email is already Taken",
								Notification.TYPE_ERROR_MESSAGE);
					}
				}

			}
		});

	}

	public void clearForm() {
		companyName.setValue("");
		companyEmail.setValue("");
	}
}
